﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1_5
{
    public partial class Iudata : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                ViewState["IsActive"] = int.TryParse(Request.QueryString["id"], out int id);


                if ((bool)ViewState["IsActive"])
                {
                    ViewState["Id"] = id;

                    string sql = "select * from Articles where id=" + id;
                    var table = DbHelper.GetData(sql);
                    TextBox1.Text = table.Rows[0].ItemArray[1].ToString();
                    TextBox2.Text = table.Rows[0].ItemArray[2].ToString();
                    TextBox3.Text = table.Rows[0].ItemArray[3].ToString();
                    TextBox4.Text = table.Rows[0].ItemArray[8].ToString();

                }
            }
        }
        /// <summary>
        /// 保存并返回
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void sBtn_Click(object sender, EventArgs e)
        {
            var title = TextBox1.Text;
            var author = TextBox2.Text;
            var content = TextBox3.Text;
            var remarks = TextBox4.Text;

            string sql = "";

            if ((bool)ViewState["IsActive"])
            {
                sql = string.Format("update Articles set Title='{0}',Author='{1}',Content='{2}',Remarks='{3}' where id={4}", title, author, content, remarks, ViewState["Id"].ToString());
                var res = DbHelper.UpdateData(sql);

                if (res < 0)
                {
                    Response.Write("<script>alert('编辑失败')</script>");
                }
                else
                {
                    Response.Redirect("Default.aspx?cancel=false");
                }
            }
            else
            {

                sql = string.Format("insert into Articles(Title,Author,Content,Remarks) values('{0}','{1}','{2}','{3}')", title, author, content, remarks);
                var res = DbHelper.UpdateData(sql);

                if (res < 0)
                {
                    Response.Write("<script>alert('添加失败')</script>");
                }
                else
                {
                    Response.Redirect("Default.aspx?cancel=false");
                }
            }


        }

        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void cBtn_Click(object sender, EventArgs e)
        {
            Response.Redirect("Default.aspx?cancel=true");
        }
    }
}